package com.kevis.zhunblog.admin.controller.modules.sys;

import com.kevis.webCommon.constant.ControllerConstant;
import com.kevis.webCommon.web.domain.response.Result;
import com.kevis.webCommon.web.domain.response.module.ResultTable;
import com.kevis.webCommon.web.domain.response.module.ResultTree;
import com.kevis.zhunblog.admin.controller.base.BaseController;
import com.kevis.zhunblog.core.entities.PowerMenuEntity;
import com.kevis.zhunblog.service.PowerMenuService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

import static com.kevis.webCommon.web.domain.response.Result.decide;
import static com.kevis.webCommon.web.domain.response.Result.failure;

/**
 * SysPowerController
 *
 * @Author kevis
 * @Date 2023/4/2 20:49
 */
@RestController
@Api(tags = {"系统权限"})
@RequestMapping(ControllerConstant.API_SYSTEM_PREFIX + "power")
public class SysPowerController extends BaseController {

    /**
     * 基础路径
     */
    private String MODULE_PATH = "system/power/";

    @Autowired
    private PowerMenuService powerMenuService;

    /**
     * 获取权限列表视图
     *
     * @return
     */
    @GetMapping("main")
    public ModelAndView main() {
        return jumpPage(MODULE_PATH + "main");
    }

    /**
     * 获取权限列表数据
     *
     * @return
     */
    @PostMapping("list")
    public ResultTable postlist() {
//        List<SysMenu> menuList = powerMenuService.getMenuList();
//        ResultTable resultTable = ResultTable.pageTable(menuList.size(), menuList);
//        return resultTable;
        List<PowerMenuEntity> list = powerMenuService.list();
        return treeTable(list);
    }

    /**
     * 获取权限新增视图
     *
     * @param model
     * @return
     */
    @GetMapping("add")
    public ModelAndView add(Model model, @RequestParam(name = "parentId", required = false, defaultValue = "0") Integer parentId) {
        if (null != parentId && parentId > 0) {
            PowerMenuEntity parentEntity = powerMenuService.getById(parentId);
            if (parentEntity == null) {
                throw new RuntimeException("父类id不存在");
            }
        }
        PowerMenuEntity powerMenuEntity = new PowerMenuEntity();
        powerMenuEntity.setParentId(parentId);
//        if (Objects.equals(parentEntity.getMenuCode(), "0")) {
//            powerMenuEntity.setMenuCode("0");
//        } else if ("1".equals(parentEntity.getMenuCode())) {
//            powerMenuEntity.setMenuCode("2");
//        }
        model.addAttribute("sysPower", powerMenuEntity);
        return jumpPage(MODULE_PATH + "edit");
    }

    /**
     * Describe: 获取父级权限选择数据
     * Param powerMenuEntity
     * Return Result
     */
    @PostMapping("selectParent")
    public ResultTree selectParent(PowerMenuEntity powerMenuEntity) {
        ResultTree result = new ResultTree();
        List<PowerMenuEntity> list = powerMenuService.listMenu(powerMenuEntity);
        PowerMenuEntity basePower = new PowerMenuEntity();
        basePower.setTitle("顶级权限");
        basePower.setId(0);
        basePower.setParentId(-1);
        list.add(basePower);
        result.setData(list);
//        Set<TreeSelectVo> set = list.stream().map(t -> {
//            TreeSelectVo tree = new TreeSelectVo();
//            tree.setId(t.getId().toString());
//            tree.setField(t.getMenuCode());
//            tree.setHref(t.getUrl());
//            tree.setTitle(t.getTitle());
//            //tree.setChildren();
//            return tree;
//        }).collect(Collectors.toSet());
//        result.setData(set);
        return result;
        //return dataTree(list);
    }

    /**
     * Describe: 保存权限信息
     * Param: SysPower
     * Return: ResuBean
     */
    @PostMapping("add")
    //@PreAuthorize("hasPermission('/system/power/add','sys:power:add')")
    public Result save(PowerMenuEntity sysPower) {
        if (sysPower.getParentId() == null) {
            return failure("请选择上级菜单");
        }
        PowerMenuEntity parentModel = powerMenuService.getById(sysPower.getParentId());
        int menuLevel = parentModel != null ? parentModel.getMenuLevel() + 1 : 1;
        sysPower.setStatus(0);//默认设置启用状态
        sysPower.setMenuLevel(menuLevel);
        sysPower.setGuid(UUID.randomUUID().toString());
        //sysPower.setPowerId(SequenceUtil.makeStringId());
        boolean result = powerMenuService.save(sysPower);
        return decide(result);
    }

    /**
     * Describe: 获取权限修改视图
     * Param ModelAndView
     * Return 权限修改视图
     */
    @GetMapping("edit")
    //@PreAuthorize("hasPermission('/system/power/edit','sys:power:edit')")
    public ModelAndView edit(Model model, String powerId) {
        model.addAttribute("sysPower", powerMenuService.getById(powerId));
        return jumpPage(MODULE_PATH + "edit");
    }

    /**
     * Describe: 修改权限信息
     * Param SysPower
     * Return 执行结果
     */
    @PutMapping("edit")
    //@PreAuthorize("hasPermission('/system/power/edit','sys:power:edit')")
    //public Result update(@RequestBody PowerMenuEntity sysPower) {
    public Result update(PowerMenuEntity sysPower) {
        if (sysPower.getParentId() == null) {
            return failure("请选择上级菜单");
        }
        sysPower.setUpdateTime(LocalDateTime.now());
        boolean result = powerMenuService.updateById(sysPower);
        return decide(result);
    }

    /**
     * Describe: 根据 id 进行删除
     * Param id
     * Return Result
     */
    @DeleteMapping("remove/{id}")
    @PreAuthorize("hasPermission('/system/power/remove','sys:power:remove')")
    public Result remove(@PathVariable String id) {
        if (powerMenuService.selectByParentId(id).size() > 0) {
            return failure("请先删除下级权限");
        }
        boolean result = powerMenuService.remove(id);
        return decide(result);
    }

    /**
     * Describe: 根据 Id 开启用户
     * Param powerId
     * Return Result
     */
    @PutMapping("show")
    public Result enable(@RequestBody PowerMenuEntity sysPower) {
        sysPower.setIsShow(true);
        boolean result = powerMenuService.updateById(sysPower);
        return decide(result);
    }

    /**
     * Describe: 根据 Id 禁用用户
     * Param powerId
     * Return Result
     */
    @PutMapping("hide")
    public Result disable(@RequestBody PowerMenuEntity sysPower) {
        sysPower.setIsShow(false);
        boolean result = powerMenuService.updateById(sysPower);
        return decide(result);
    }
}
